<?php

require_once(__DIR__ . '/../vendor/autoload.php');

use Beanbun\Beanbun;
use Beanbun\Lib\Db;

Db::$config = [
    'kmmovie' => [
        'server' => '10.1.1.247',
        'port' => '3306',
        'username' => 'root',
        'password' => 'root',
        'database_name' => 'kmmovie2',
        'database_type' => 'mysql',
        'charset' => 'utf8',
    ],
];


$beanbun = new Beanbun;
$beanbun->name = 'maoyan';
$beanbun->count = 10;
$beanbun->interval = 30;     // 间隔时间
$beanbun->seed = [
    'http://maoyan.com/films',
];
$beanbun->logFile = __DIR__ . '/maoyan_access' . date('Y-m-d-H-i-s') . '.log';
$beanbun->urlFilter = [
    '/^http:\/\/maoyan.com\/films\/(\d*)$/',
    '/^http:\/\/maoyan.com\/films\?yearId=(\d*)/',
];
// 设置队列
$beanbun->setQueue('memory', [
    'host' => '127.0.0.1',
    'port' => '2207'
]);
//$beanbun->userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3026.3 Safari/537.36';
$beanbun->startWorker = function ($beanbun) {
    $beanbun->log("startWorker worker id {$beanbun->id} start success.");
};

$beanbun->beforeDownloadPage = function($beanbun) {
//    $beanbun->log("user-agent is {$beanbun->options['headers']['user-agent']}.");
    $beanbun->log("beforeDownloadPage worker id {$beanbun->id} $beanbun->url");
    $beanbun->options['proxy'] = '10.1.1.247:8888';
    $beanbun->options['verify'] = false;
    $beanbun->options['cookies'] = \GuzzleHttp\Cookie\CookieJar::fromArray([
        '_lxsdk'=>'15bb54bb030c8-08d75139bf0023-1e1b7158-1fa400-15bb54bb0308a',
        'lt'=>'2YhadW8uQeKuMUbgmPPQ1n6idDIAAAAA7wMAAAqInRnZi7zvXOKHAXmMAZoFXcFQqeJPIw3hJiBFtHAHt3Ls6-hfCOTQYo1ELpc9aQ',
        'lt.sig'=>'GLPlsjSxAYvdAlwqqvth266ErXI',
        '_lx_utm'=>'',
        '__mta'=>'252665782.1493395288835.1493633310264.1493640478338.88',
        '_lxsdk_s'=>'0495a39ea62e28584496444baa51%7C%7C4',
    ], '.maoyan.com');
};

$beanbun->afterDownloadPage = function ($beanbun) {
    $beanbun->log("afterDownloadPage worker id {$beanbun->id} $beanbun->url");

    $beanbun->log(str_replace(array("\r", "\r\n", "\n", '    '), '',  $beanbun->page));

    try{
        if (preg_match('/^http:\/\/maoyan.com\/films\/(\d*)$/', $beanbun->url) !== false && $beanbun->page) {
            $maoyanPhpRow = Db::instance('kmmovie')->select("km_tl_maoyan_python2", [
                "id",
                "url"
            ], [
                "url" => $beanbun->url
            ]);

            if (empty($maoyanPhpRow)) {
                Db::instance('kmmovie')->insert("km_tl_maoyan_python2", [
                    "url" => $beanbun->url,
                    "content" => str_replace(array("\r", "\r\n", "\n", '    '), '', $beanbun->page)
                ]);
            }
        }
    }catch (\Exception $e){
        $beanbun->log($e->getCode().':'.$e->getMessage());
    }



};

$beanbun->stopWorker = function ($beanbun) {
    $beanbun->log("beanbun worker id {$beanbun->id} stop success.");
};

$beanbun->start();